package com.example.mall.common.model;

import com.example.mall.common.constants.BaseEnum;
import com.example.mall.common.constants.CodeEnum;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

import java.io.Serializable;

/**
 * @author Mickey
 * @since 2020.08.08
 */
@ApiModel(
        value = "接口返回对象",
        description = "接口返回对象"
)
@Data
public class Result<T> implements Serializable {

    /**
     * 请求id
     */
    private String requestId;
    @ApiModelProperty("成功标志")
    private boolean success;
    @ApiModelProperty("时间戳")
    private Long timestamp = System.currentTimeMillis();
    @ApiModelProperty("返回代码")
    private Integer code;
    @ApiModelProperty("返回处理消息")
    private String msg;
    @ApiModelProperty("返回数据对象")
    private T data;

    public static <T> Result<T> OK() {
        Result<T> result = new Result<>();
        result.success = true;
        result.setCode(CodeEnum.SUCCESS.getCode());
        result.setMsg(CodeEnum.SUCCESS.getName());
        return result;
    }

    public static <T> Result<T> OK(T data) {
        Result<T> result = new Result<>();
        result.setSuccess(true);
        result.setCode(CodeEnum.SUCCESS.getCode());
        result.setData(data);
        result.setMsg(CodeEnum.SUCCESS.getName());
        return result;
    }

    public static Result ofSuccess(Object payload) {
        Result result = new Result();
        result.success = true;
        result.setData(payload);
        result.setCode(CodeEnum.SUCCESS.getCode());
        result.setMsg(CodeEnum.SUCCESS.getName());
        return result;
    }

    public static Result ofError() {
        Result result = new Result();
        result.success = false;
        result.setCode(CodeEnum.FAIL.getCode());
        result.setMsg(CodeEnum.FAIL.getName());
        return result;
    }

    public static Result ofError(BaseEnum<?> codeEnum) {
        Result result = new Result();
        result.success = false;
        result.setCode(codeEnum.getCode());
        result.setMsg(codeEnum.getName());
        return result;
    }

    public static Result ofError(String msg) {
        Result result = new Result();
        result.success = false;
        result.setCode(CodeEnum.FAIL.getCode());
        result.setMsg(msg);
        return result;
    }
}
